﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media.Animation;

namespace Red.Controls
{
    /// <summary>
    /// A button that is invisible until the mouse hovers over an activating ui element
    /// </summary>
    public class HidingButton : Button
    {
        #region Public Properties

        public static readonly DependencyProperty RevealingElementProperty = DependencyProperty.Register( "RevealingElement", typeof( UIElement ), typeof( HidingButton ), new PropertyMetadata( RevealingElementChanged ) );
        public static readonly DependencyProperty KeepHiddenProperty = DependencyProperty.Register( "KeepHidden", typeof( bool ), typeof( HidingButton ) );

        /// <summary>
        /// The HidingButton will be made visible when the mouse is over the RevealingElement
        /// </summary>
        public UIElement RevealingElement
        {
            get { return (UIElement)GetValue( RevealingElementProperty ); }
            set { SetValue( RevealingElementProperty, value ); }
        }

        /// <summary>
        /// Prevent the button from automatically being revealed.
        /// </summary>
        public bool KeepHidden
        {
            get { return (bool)GetValue( KeepHiddenProperty ); }
            set { SetValue( KeepHiddenProperty, value ); }
        }

        #endregion Public Properties

        #region C-Tor

        public HidingButton()
        {
            Opacity = 0;
        }

        #endregion C-Tor

        #region Event Handlers

        private static void RevealingElementChanged( DependencyObject d, DependencyPropertyChangedEventArgs e )
        {
            HidingButton button = (HidingButton)d;

            if( e.OldValue != null )
            {
                UIElement previous = (UIElement)e.OldValue;

                previous.MouseEnter -= button.HidingButton_MouseEnter;
                previous.MouseLeave -= button.HidingButton_MouseLeave;
            }

            UIElement element = (UIElement)e.NewValue;
            element.MouseEnter += button.HidingButton_MouseEnter;
            element.MouseLeave += button.HidingButton_MouseLeave;
        }

        private void HidingButton_MouseEnter( object sender, MouseEventArgs e )
        {
            if( !KeepHidden )
            {
                DoubleAnimation anim = new DoubleAnimation( 1, TimeSpan.FromSeconds( 0.25 ) );
                BeginAnimation( OpacityProperty, anim );
            }
        }

        private void HidingButton_MouseLeave( object sender, MouseEventArgs e )
        {
            DoubleAnimation anim = new DoubleAnimation( 0, TimeSpan.FromSeconds( 0.25 ) );
            BeginAnimation( OpacityProperty, anim );
        }

        #endregion Event Handlers
    }
}
